import React from 'react'
import { Icon, Menu } from 'antd'
import { connect } from 'dva/index'
import { routerRedux } from 'dva/router'
import { unionBy } from 'lodash'


@connect(({ menu }) => ({
  menu,
}))
class SideMenu extends React.PureComponent {

  handleMenuClick = ({ item }) => {
    const { useNavTab, curNavTab } = this.props.menu
    const menuItem = item.props.menuitem
    this.saveCurNavTab(menuItem)
    if (useNavTab) {
      this.saveNavTabList(menuItem)
    } else if (menuItem.path !== curNavTab.path) {
      this.props.dispatch(routerRedux.push(menuItem.path))
    }
  }

  saveCurNavTab = (menuItem) => {
    let { curNavTab } = this.props.menu
    if (curNavTab.path !== menuItem.path) {
      this.props.dispatch({
        type: 'menu/saveCurNavTab',
        payload: menuItem,
      })
    }
  }

  saveNavTabList = (menuItem) => {
    let { navTabList, curNavTab } = this.props.menu
    if (curNavTab.name !== menuItem.name) {
      navTabList = unionBy(navTabList, [menuItem], 'path')
      this.props.dispatch({
        type: 'menu/saveNavTabList',
        payload: navTabList,
      })
    }
  }

  render() {
    const { menuData, isAdmin, userMenu } = this.props

    const userMenuObj = {}
    userMenu.forEach(menu => { userMenuObj[menu] = menu })

    let userMenuData = menuData
    if (!isAdmin) {
      userMenuData = menuData.filter(menu => userMenuObj[menu.path])
    }

    return (
      <Menu
        theme="dark"
        mode="inline"
        onClick={this.handleMenuClick}
        defaultSelectedKeys={['1']}>
        {userMenuData.map(item => (
          <Menu.SubMenu
            key={item.path}
            title={<span><Icon type={item.icon || 'appstore'} /><span>{item.name}</span></span>}
          >
            {item.children.map(subItem => (
              <Menu.Item key={subItem.path} menuitem={subItem}>
                <div>
                  <Icon type={subItem.icon || 'appstore'} />
                  {subItem.name}
                </div>
              </Menu.Item>
            ))}
          </Menu.SubMenu>
        ))}
      </Menu>
    )
  }
}

export default SideMenu
